#ifndef FIRMWAREUPGRADEDIALOG_H
#define FIRMWAREUPGRADEDIALOG_H

#include <QDialog>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QLabel>
#include <QPushButton>
#include <QProgressBar>
#include <QFileDialog>
#include <QLineEdit>
#include <QCheckBox>
#include <QTextEdit>
#include <QGroupBox>
#include <QTimer>
#include <QMessageBox>
#include <QCryptographicHash>
#include <QFileInfo>
#include "../core/device/devicemanager.h"

class FirmwareUpgradeDialog : public QDialog
{
    Q_OBJECT

public:
    explicit FirmwareUpgradeDialog(const QString &ipAddress, DeviceManager *deviceManager, QWidget *parent = nullptr);

private slots:
    void onSelectFileClicked();
    void onStartUpgradeClicked();
    void onCancelClicked();
    
    // 设备管理器信号槽
    void onFirmwareUploadProgress(const QString &ipAddress, int progress);
    void onFirmwareUploadComplete(const QString &ipAddress);
    void onFirmwareUpgradeStarted(const QString &ipAddress, const QString &upgradeId, const QString &status, int estimatedDuration);
    void onFirmwareUpgradeStatusReceived(const QString &ipAddress, const QString &status, int progress, const QString &message);
    void onFirmwareUpgradeError(const QString &ipAddress, const QString &errorMessage);
    
    // 定时器槽函数
    void onStatusCheckTimer();

private:
    void setupUI();
    void connectSignals();
    void updateUI();
    void setUIEnabled(bool enabled);
    void uploadFirmwareFile();
    QString calculateMD5(const QString &filePath);
    void sendNextChunk();
    void addLog(const QString &message);

    // 状态枚举
    enum UpgradeState {
        Idle,           // 空闲状态
        Uploading,      // 上传中
        UploadComplete, // 上传完成
        Upgrading,      // 升级中
        Success,        // 升级成功
        Failed          // 升级失败
    };
    
private:
    QString m_ipAddress;
    DeviceManager *m_deviceManager;
    UpgradeState m_state;
    QString m_selectedFilePath;
    QString m_firmwareVersion;
    bool m_forceUpgrade;
    
    // UI控件
    QGroupBox *m_fileSelectionGroup;
    QLineEdit *m_filePathEdit;
    QPushButton *m_selectFileButton;
    QLabel *m_fileSizeLabel;
    QLabel *m_fileMD5Label;
    
    QGroupBox *m_upgradeOptionsGroup;
    QLineEdit *m_versionEdit;
    QCheckBox *m_forceCheckBox;
    
    QGroupBox *m_progressGroup;
    QProgressBar *m_uploadProgressBar;
    QProgressBar *m_upgradeProgressBar;
    QLabel *m_statusLabel;
    QTextEdit *m_logTextEdit;
    
    QPushButton *m_startButton;
    QPushButton *m_cancelButton;
    
    // 定时器用于定期查询升级状态
    QTimer *m_statusCheckTimer;
    
    // 文件上传相关
    QByteArray m_fileData;
    int m_totalChunks;
    int m_currentChunk;
    int m_chunkSize;  // 64KB chunks
};

#endif // FIRMWAREUPGRADEDIALOG_H